package com.book.modules.filter;

import com.book.common.api.entity.CurrentUser;
import com.book.common.result.RestResponse;
import com.book.common.util.SpringContextUtil;
import com.book.modules.annotation.InjectionCurrentUser;
import com.book.modules.helper.CurrentUserHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Description： 1、根据InjectionCurrentUser注解判断是否需要注入当前用户信息
 * 2、如果需要注入当前用户信息，根据token或者cookies获取用户信息，
 * 如果用户信息不存在，则创建一个用户信息，填充token信息
 *
 * @Author： leo.xiong
 * @CreateDate： 2020/04/22 10:49
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Slf4j
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {

    private final CurrentUserHelper currentUserHelper = SpringContextUtil.getBean(CurrentUserHelper.class);

    public CurrentUserArgumentResolver() {
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        InjectionCurrentUser value = parameter.getMethodAnnotation(InjectionCurrentUser.class);
        return value != null && value.value() ? true : false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        if (parameter.getParameterType().equals(CurrentUser.class)) {
            HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
            String token = currentUserHelper.getRequestToken(request);
            RestResponse<CurrentUser> currentUserRestResponse = currentUserHelper.getUserByToken(token);
            CurrentUser currentUser = new CurrentUser();
            if (currentUserRestResponse.isSuccess()) {
                currentUser = currentUserRestResponse.getData();
            } else {
                currentUser.setToken(token);
            }
            return currentUser;
        } else {
            return parameter;
        }
    }
}
